package common;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by lx on 2017/8/1.
 *  线程池创建
 */
public class ThreadPool {
    //默认线程次数量
    private static int work_num = 5;

    private WorkThread[] workThreads;

    //任务队列
    private static List<Runnable> taskQueue = new LinkedList<>();

    private static ThreadPool threadPool;

    private ThreadPool(int work_num){
        this.work_num = work_num;
        //初始化工作线程
        workThreads = new WorkThread[work_num];
        for (int i = 0 ; i < work_num ; i++){
            workThreads[i] = new WorkThread();
            workThreads[i].start();
        }
    }

    /**
     * 単例 获取线程池对象
     * @param work_num : 线程数量
     * @return
     */
    public static ThreadPool getThreadPool(int work_num){
        if(threadPool != null){
            return threadPool;
        }
        synchronized (ThreadPool.class){
            if(threadPool != null){
                return threadPool;
            }
            threadPool = new ThreadPool(work_num);
        }
        return threadPool;
    }

    public void eccute(Runnable runnable){
        synchronized (taskQueue){
            taskQueue.add(runnable);
            taskQueue.notify();
        }
    }

    /**
     * 私有内部类
     */
    private class WorkThread extends Thread {
        @Override
        public void run() {
            Runnable r = null;
            while (true){
                synchronized (taskQueue){
                    while (taskQueue.isEmpty()) {
                        try {
                            taskQueue.wait(20);
                        }catch (Exception e){
                            System.out.println(e.getMessage());
                        }
                    }
                    if(!taskQueue.isEmpty()){
                        r = taskQueue.remove(0);
                    }
                }
                if(r != null){
                    r.run();
                }
                r = null;
            }

        }
    }
}




class test{
    public static void main(String[] args) {
        for (int i = 0 ;i < 50 ; i++){
            new Thread(){
                @Override
                public void run() {
                    ThreadPool threadPool = ThreadPool.getThreadPool(3);
                    threadPool.eccute(new Thread(){
                        @Override
                        public void run() {
                            try {
                                TimeUnit.SECONDS.sleep(5);
                                System.out.println(Thread.currentThread().getName());
                            }catch (Exception e){

                            }
                        }
                    });
                }
            }.start();
        }

    }
}